<!--
 * @Author: luqinghua
 * @Date: 2025-03-23 19:17:08
 * @LastEditors: luqinghua
 * @LastEditTime: 2025-03-23 21:09:26
 * @FilePath: \pywebview-vue\web\src\views\demo.vue
 * @Description: 
-->
<template>
  <h3>pywebview集成vue+ts示例</h3>
  <el-form label-width="auto" :model="formLabelAlign" style="max-width: 600px">
    <el-form-item label="版本">
      <el-input v-model="formLabelAlign.version" disabled />
    </el-form-item>
    <el-form-item label="说明">
      <el-input v-model="formLabelAlign.description" />
    </el-form-item>
    <el-form-item label="环境">
      <el-input v-model="formLabelAlign.environment" disabled />
    </el-form-item>
    <el-form-item label="其他说明">
      <el-input v-model="formLabelAlign.others" type="textarea" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" plain @click="getMessage">获取python接口数据</el-button>
      <el-button type="primary" @click="clearMessage">清空数据</el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" plain @click="openNewWindow">调用pywebview打开新窗口</el-button>
      <el-button type="primary" @click="saveData">提交数据给后台</el-button>
    </el-form-item>
  </el-form>

  {{ tips }}
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
// import { ElMessageBox } from 'element-plus';

let formLabelAlign = reactive({
  version: 'V1.0.0',
  description: '',
  environment: '',
  others: '',
});

const tips = ref('');

onMounted(() => {});

//  获取pywebview接口
const getMessage = async () => {
  // 检测是否为 pywebview 环境
  if ((window as any).pywebview) {
    try {
      const res = await (window as any).pywebview.api.getMessage();
      if (res) {
        Object.assign(formLabelAlign, res);
        tips.value = res;
      } else {
        tips.value = '获取信息失败';
      }
    } catch (error) {
      console.error('调用pywebview接口时出错:', error);
      tips.value = '发生错误，请稍后再试' + error;
    }
  } else {
    tips.value = '当前不是 pywebview 环境';
  }
};

const saveData = async () => {
  try {
    // 这里可以添加实际的提交逻辑，例如发送请求到后端
    const res = await (window as any).pywebview?.api?.saveMessage(formLabelAlign);
    tips.value = res;
  } catch (error) {
    tips.value = error as string;
  }
};

const clearMessage = () => {
  formLabelAlign.description = '';
  formLabelAlign.environment = '';
  formLabelAlign.others = '';
};

//调用pywebview打开新窗口
const openNewWindow = async () => {
  if ((window as any).pywebview) {
    const res = await (window as any).pywebview.api.open_new_window({
      title: 'pyth集成vue示例',
      url: 'https://blog.csdn.net/lqh4188',
    });
  } else {
    tips.value = '当前不是 pywebview 环境';
    // ElMessageBox.alert('当前不是 pywebview 环境');
  }
};
</script>
